<template>
  <div id="app">
    <div v-for="item of carts" :key="item.id">
      <van-card
        :price="item.productPrice"
        :desc="item.productInfo"
        :title="item.productName"
        :thumb="item.productCover"
      >
        <template #num>
          <van-stepper v-model="item.productCount" />
          
        </template>
        <template #footer>
          <van-checkbox
            @change="handleItem"
            class="box"
            v-model="item.isSelected"
          ></van-checkbox>
          <van-tag plain type="danger"
            >小计：{{
              (item.productCount * item.productPrice) | handleSum
            }}</van-tag
          >
        </template>
      </van-card>
    </div>
    <van-submit-bar
      :price="sum()"
      button-text="提交订单"
      class="footer"
    >
      <van-checkbox v-model="allChecked" @click="changeAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      carts: [],
      allChecked: true,
    };
  },
  mounted() {
    this.$http("/cart").then((res) => {
      this.carts = res.data;
    });
  },
  filters: {
    handleSum(val) {
      return "$" + val.toFixed(2);
    },
  },
  methods: {
    sum() {
      var all = 0;
      this.carts.forEach((item) => {
        if (item.isSelected) {
          all += item.productCount * item.productPrice * 100;
        }
      });
      return all;
    },
    handleItem() {
      /* 改变allChecked */
      var allChecked = this.carts.every(item => item.isSelected);
      this.allChecked = allChecked;
    },
    changeAll(){
      console.log(this.allChecked);
      this.carts.forEach(item=>{
        item.isSelected = this.allChecked
      })
    }

  },
};
</script>

<style>
#app {
  width: 800px;
  margin: auto;
  position: relative;
}
.footer {
  width: 800px;
  margin-left: 280px;
}
.box {
  position: absolute;
  top: 40%;
  left: 0;
}
.van-card {
  padding-left: 30px;
}
</style>
